﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.ImageEditor;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
using XCI.Core;
using XCI.Helper;

namespace XCI.Windows
{
    public partial class FrmImagePreview : BaseForm
    {
        private LoadingMask loadingPanel;
        private List<string> _fileList = new List<string>();
        private string _path;
        private Func<string, Task<Image>> _loadImageCallback;
        private Image _image;
        private Image _original;
        private Image _current;

        public FrmImagePreview()
        {
            InitializeComponent();
        }

        public FrmImagePreview(string path, List<string> fileList = null, Func<string, Task<Image>> loadImageCallback = null)
        {
            InitializeComponent();
            _fileList = fileList;
            _path = path;
            _loadImageCallback = loadImageCallback;
        }

        public FrmImagePreview(string path)
        {
            InitializeComponent();
            _path = path;
        }
        public FrmImagePreview(Image image)
        {
            InitializeComponent();
            _image = image;
        }

        private async Task LoadImage()
        {
            if (_loadImageCallback != null && !string.IsNullOrEmpty(_path))
            {
                try
                {
                    loadingPanel.Show();
                    pictureEdit1.Image = await _loadImageCallback.Invoke(_path);
                }
                finally
                {
                    SetPictureZoomPercent();
                    loadingPanel.Hide();
                }
            }
            else if (!string.IsNullOrEmpty(_path))
            {
                pictureEdit1.LoadAsync(_path);
            }
            else if (_image != null)
            {
                pictureEdit1.Image = _image;
                SetPictureZoomPercent();
            }
        }

        private void SetButtonStatus()
        {
            var hasImage = pictureEdit1.Image != null;

            btnPre.Enabled = _fileList.Count > 0 && _fileList.IndexOf(_path) > 0;
            btnNext.Enabled = _fileList.Count > 0 && _fileList.IndexOf(_path) < _fileList.Count - 1;

            btnShrink.Enabled = pictureEdit1.Properties.ZoomPercent > 5 && hasImage;
            btnZoomIn.Enabled = pictureEdit1.Properties.ZoomPercent < 1600 && hasImage;
            btnActual.Enabled = Convert.ToInt32(pictureEdit1.Properties.ZoomPercent) != 100 && hasImage;

            btnEdit.Enabled = hasImage;
            btnExport.Enabled = hasImage;

            btnRestore.Enabled = _current != null && _original != null;
            btnRotateLeft.Enabled = hasImage;
            btnRotateRight.Enabled = hasImage;

            btnBlackAndWhite.Enabled = hasImage;
            btnInverted.Enabled = hasImage;
            btnRelievo.Enabled = hasImage;
            btnMirror.Enabled = hasImage;
        }

        private void SetImage(Func<Image, Image> callback)
        {
            Image old = null;
            if (_current == null)
            {
                _current = _original;
            }
            else
            {
                old = _current;
            }

            _current = callback?.Invoke(_current);
            pictureEdit1.Image = _current;
            old?.Dispose();
            SetButtonStatus();
        }

        private void SetPictureZoomPercent()
        {
            _original = pictureEdit1.Image;
            if (pictureEdit1.Image != null)
            {
                var percent = CalcImageZoomPercent(pictureEdit1.Image);
                pictureEdit1.Properties.ZoomPercent = percent;
                statusZoomPercent.Caption = $"{pictureEdit1.Properties.ZoomPercent:##0}%";
            }
        }

        private async void FrmImagePreview_Load(object sender, EventArgs e)
        {
            loadingPanel = new LoadingMask(this);
            await LoadImage();
            SetButtonStatus();
        }

        private void PictureEdit1_LoadCompleted(object sender, EventArgs e)
        {
            SetPictureZoomPercent();
        }

        private async void BtnPre_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var index = _fileList.IndexOf(_path);
            _path = _fileList[index - 1];
            await LoadImage();
            SetButtonStatus();
        }

        private async void BtnNext_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var index = _fileList.IndexOf(_path);
            _path = _fileList[index + 1];
            await LoadImage();
            SetButtonStatus();
        }

        private void BtnShrink_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (pictureEdit1.Properties.ZoomPercent <= 5)
            {
                SetButtonStatus();
                return;
            }
            var percent = pictureEdit1.Properties.ZoomPercent - 5;
            pictureEdit1.Properties.ZoomPercent = percent;
            SetButtonStatus();
        }

        private void BtnZoomIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (pictureEdit1.Properties.ZoomPercent >= 1600)
            {
                SetButtonStatus();
                return;
            }
            var percent = pictureEdit1.Properties.ZoomPercent + 5;
            pictureEdit1.Properties.ZoomPercent = percent;
            SetButtonStatus();
        }

        private void BtnActual_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            pictureEdit1.Properties.ZoomPercent = 100;
            SetButtonStatus();
        }


        private void BtnRotate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.Rotate270FlipNone);
                return img;
            });
        }

        private void BtnRotateRight_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.Rotate90FlipNone);
                return img;
            });
        }

        private void BtnExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (pictureEdit1.Image == null)
            {
                MessageBoxHelper.ShowWarn("当前没有图片");
                return;
            }

            this.saveFile.FileName = Path.GetFileName(_path);
            if (this.saveFile.ShowDialog() == DialogResult.OK)
            {
                FileInfo fileInfo = new FileInfo(this.saveFile.FileName);
                FileStream fileStream = null;
                try
                {
                    if (fileInfo.Exists)
                        fileInfo.Delete();
                    fileStream = new FileStream(this.saveFile.FileName, FileMode.Create);
                    ImageFormat format;
                    switch (this.saveFile.FilterIndex)
                    {
                        case 1:
                            format = ImageFormat.Bmp;
                            break;
                        case 2:
                            format = ImageFormat.Gif;
                            break;
                        case 4:
                            format = ImageFormat.Png;
                            break;
                        default:
                            format = ImageFormat.Jpeg;
                            break;
                    }
                    pictureEdit1.Image.Save(fileStream, format);
                    //MessageBoxHelper.ShowWarn("导出成功");
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show(ex.Message, ex.Source, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                finally
                {
                    fileStream?.Close();
                }
            }
        }

        private void BtnMirror_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            SetImage(p =>
            {
                var img = new Bitmap(p);
                img.RotateFlip(RotateFlipType.RotateNoneFlipX);
                return img;
            });
        }

        private void BtnRestore_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (_current != null)
            {
                _current.Dispose();
                _current = null;
                pictureEdit1.Image = _original;
                SetButtonStatus();
            }
        }

        private void BtnBlackAndWhite_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                loadingPanel.Show();
                SetImage(p => ImageHelper.HeiBai(p));
            }
            finally
            {
                loadingPanel.Hide();
                SetButtonStatus();
            }

        }

        private void BtnInverted_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                loadingPanel.Show();
                SetImage(ImageHelper.FanSe);
            }
            finally
            {
                loadingPanel.Hide();
                SetButtonStatus();
            }
        }

        private void BtnRelievo_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                loadingPanel.Show();
                SetImage(ImageHelper.FuDiao);
            }
            finally
            {
                loadingPanel.Hide();
                SetButtonStatus();
            }
        }

        private void BtnEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (ImageEditorDialog imageEditorDialog = new ImageEditorDialog())
            {
                Image old = null;
                if (_current == null)
                {
                    _current = _original;
                }
                else
                {
                    old = _current;
                }
                var dialogResult = imageEditorDialog.ShowDialog(_current, FindForm());
                if (dialogResult == DialogResult.OK)
                {
                    _current = imageEditorDialog.Image;
                    pictureEdit1.Image = _current;
                    old?.Dispose();
                    SetButtonStatus();
                }
            }
        }

        private void pictureEdit1_ZoomPercentChanged(object sender, EventArgs e)
        {
            statusZoomPercent.Caption = $"{pictureEdit1.Properties.ZoomPercent:##0}%";
        }

        private double CalcImageZoomPercent(Image img)
        {
            if (img == null)
            {
                return 100;
            }
            var widthRatio = pictureEdit1.Width * 1d / img.Width;
            var heightRatio = pictureEdit1.Height * 1d / img.Height;
            var ratio = widthRatio < heightRatio ? widthRatio : heightRatio;
            if (ratio >= 1) ratio = 1;
            if (ratio <= 0.05) ratio = 0.05;
            return Math.Round(ratio * 100, 0);
        }

        private void FrmImagePreview_SizeChanged(object sender, EventArgs e)
        {
            if (pictureEdit1.Image != null)
            {
                var percent = CalcImageZoomPercent(pictureEdit1.Image);
                pictureEdit1.Properties.ZoomPercent = percent;
            }

        }

    }
}
